package huxibianjie.com.lbscandroid.task;


import java.io.IOException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import huxibianjie.com.lbscandroid.BuildConfig;
import huxibianjie.com.lbscandroid.MyApplication;
import huxibianjie.com.lbscandroid.R;
import huxibianjie.com.lbscandroid.util.MyLog;
import huxibianjie.com.lbscandroid.util.NDKUtil;
import huxibianjie.com.lbscandroid.util.StringUtils;
import huxibianjie.com.lbscandroid.util.security.BASE64Encoder;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 签名拦截器
 * Created by CZF on 2018/7/23.
 */
class SignInterceptor implements Interceptor {
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private static final String TIME_STAMP = "timeStamp";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put(TIME_STAMP, String.valueOf(System.currentTimeMillis()));
        Request.Builder requestBuilder = request.newBuilder();
        if (request.body() instanceof FormBody) {
            FormBody.Builder newFormBody = new FormBody.Builder();
            FormBody oldFormBody = (FormBody) request.body();
            if (oldFormBody != null) {
                newFormBody.add(TIME_STAMP, paramsMap.get(TIME_STAMP));
                for (int i = 0; i < oldFormBody.size(); i++) {
                    paramsMap.put(oldFormBody.name(i), oldFormBody.value(i));
                    newFormBody.add(oldFormBody.name(i), oldFormBody.value(i));
                }
                newFormBody.add("sign", getSign(paramsMap));
                requestBuilder.method(request.method(), newFormBody.build());
            }
        }
        MyLog.d("task", request.toString());
        Request newRequest = requestBuilder.build();
        return chain.proceed(newRequest);
    }

    private String getSign(Map<String, String> values) {
        List<String> params = new ArrayList<>();
        for (Map.Entry<String, String> entry : values.entrySet()) {
            params.add(entry.getKey() + "=" + entry.getValue());
        }
        String[] array = params.toArray(new String[params.size()]);
        Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
        String string = StringUtils.join(array, "&");
//        string += getKey().substring(Integer.parseInt(getValue(R.string.p)));
        string += NDKUtil.getKey(MyApplication.getContext());
        return MD5(MD5(string));
    }

    private String getKey() {
        return getValue(R.string.x) + getValue(R.string.y) + getValue(R.string.z) + getValue(R.string.a) + getValue(R.string.n) + getValue(R.string.b) + getValue(R.string.o) + getValue(R.string.c) + getValue(R.string.p) + getValue(R.string.q) + getValue(R.string.d) + getValue(R.string.r) + getValue(R.string.f) + getValue(R.string.s) + getValue(R.string.a) + getValue(R.string.t) + getValue(R.string.d) + getValue(R.string.u) + getValue(R.string.f) + getValue(R.string.v) + getValue(R.string.g) + getValue(R.string.n) + getValue(R.string.w) + getValue(R.string.f) + getValue(R.string.n) + getValue(R.string.n) + getValue(R.string.g) + getValue(R.string.n) + getValue(R.string.o) + getValue(R.string.f) + getValue(R.string.n) + getValue(R.string.p) + getValue(R.string.a) + getValue(R.string.n) + getValue(R.string.q) + BuildConfig.KEY;
        //累不死你 累不死你 累不死你 ？？？？！！！！！
    }

    private String getValue(int key) {
        return MyApplication.getContext().getResources().getString(key);
    }

    /**
     * MD5加密
     */
    private String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes(UTF_8));
            byte b[] = md.digest();
            int i;
            StringBuilder buf = new StringBuilder("");
            for (byte a : b) {
                i = a;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();



           /* System.out.println("MD5(" + sourceStr + ",32) = " + result);
            System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));*/
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 将 s 进行 BASE64 编码
    private String getBASE64(String s) {
        if (s == null) {
            return null;
        }
        return (new BASE64Encoder()).encode(s.getBytes(UTF_8));
    }
}